package com.cruise.game.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cruise.game.common.api.ApiException;
import com.cruise.game.mapper.FavoriteMapper;
import com.cruise.game.mapper.GameServiceMapper;
import com.cruise.game.mapper.UserMapper;
import com.cruise.game.model.entity.Favorite;
import com.cruise.game.model.entity.GameService;
import com.cruise.game.model.entity.User;
import com.cruise.game.model.vo.common.PageResult;
import com.cruise.game.model.vo.user.FavoriteVO;
import com.cruise.game.service.user.FavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 收藏服务实现
 * 
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Resource
    private FavoriteMapper favoriteMapper;

    @Resource
    private GameServiceMapper gameServiceMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addFavorite(Long userId, Long serviceId) {
        // 验证用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ApiException("用户不存在");
        }

        // 验证服务是否存在
        GameService gameService = gameServiceMapper.selectById(serviceId);
        if (gameService == null || !"active".equals(gameService.getStatus())) {
            throw new ApiException("服务不存在或已下架");
        }

        // 验证是否已收藏
        Favorite existingFavorite = favoriteMapper.selectByUserIdAndServiceId(userId, serviceId);
        if (existingFavorite != null) {
            throw new ApiException("您已收藏过该服务，请勿重复收藏");
        }

        // 创建收藏
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setServiceId(serviceId);
        favorite.setCreatedAt(LocalDateTime.now());

        // 保存收藏
        return favoriteMapper.insert(favorite) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelFavorite(Long userId, Long serviceId) {
        // 删除收藏
        return favoriteMapper.deleteByUserIdAndServiceId(userId, serviceId) > 0;
    }

    @Override
    public PageResult<FavoriteVO> getFavoriteList(Long userId, Integer page, Integer pageSize) {
        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 查询总数
        int total = favoriteMapper.countByUserId(userId);

        // 查询收藏列表
        List<Map<String, Object>> favoriteList = favoriteMapper.selectFavoriteListWithService(userId, offset,
                pageSize.intValue());

        // 转换为VO列表
        List<FavoriteVO> favoriteVOs = favoriteList.stream().map(map -> {
            FavoriteVO vo = new FavoriteVO();
            vo.setId(Long.valueOf(map.get("id").toString()));
            vo.setCreatedAt((LocalDateTime) map.get("created_at"));

            FavoriteVO.ServiceInfo serviceInfo = new FavoriteVO.ServiceInfo();
            serviceInfo.setId(Long.valueOf(map.get("service_id").toString()));
            serviceInfo.setName((String) map.get("service_name"));
            serviceInfo.setPrice((java.math.BigDecimal) map.get("price"));
            serviceInfo.setImageUrl((String) map.get("image_url"));

            vo.setService(serviceInfo);
            return vo;
        }).collect(Collectors.toList());

        // 返回分页结果
        return PageResult.of(favoriteVOs, total, page, pageSize);
    }

    @Override
    public boolean isFavorite(Long userId, Long serviceId) {
        Favorite favorite = favoriteMapper.selectByUserIdAndServiceId(userId, serviceId);
        return favorite != null;
    }

    /**
     * 转换为收藏VO列表
     */
    private List<FavoriteVO> convertToFavoriteVOs(List<Favorite> favorites) {
        if (favorites == null || favorites.isEmpty()) {
            return new ArrayList<>();
        }

        return favorites.stream().map(favorite -> {
            FavoriteVO vo = new FavoriteVO();
            BeanUtils.copyProperties(favorite, vo);

            // 获取服务信息
            GameService gameService = gameServiceMapper.selectById(favorite.getServiceId());
            if (gameService != null) {
                FavoriteVO.ServiceInfo serviceInfo = new FavoriteVO.ServiceInfo();
                serviceInfo.setId(gameService.getId());
                serviceInfo.setName(gameService.getName());
                serviceInfo.setPrice(gameService.getPrice());
                serviceInfo.setImageUrl(gameService.getImageUrl());
                vo.setService(serviceInfo);
            }

            return vo;
        }).collect(Collectors.toList());
    }
}
